package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.properties.WeChatProperties;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.BaiduSignUtil;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrdersServiceImpl implements OrdersService {


    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;


    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.sk}")
    private String sk;
    @Value("${sky.baidu.ak}")
    private String ak;

    @Transactional //开启事务
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        //查询地址表，获取收货人信息
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //查询用户表，获取用户相关信息
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);
        if (userId == null) {
            throw new OrderBusinessException(MessageConstant.USER_NOT_LOGIN);
        }

        //查询购物车列表数据
        //只查询自己名下的购物车数据
        List<ShoppingCart> cartList = shoppingCartMapper.list(userId);
        if (cartList == null || cartList.size() == 0) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }


        //1、构造订单数据，存入orders表中
        Orders orders = new Orders();
        //拷贝属性值
        BeanUtils.copyProperties(dto, orders);
        //补充缺失的数值
        orders.setNumber(System.currentTimeMillis()+""); //订单编号，现在这个没有考虑并发的情况，所以就这样，如果要考虑加uuid或随机值
        orders.setStatus(Orders.PENDING_PAYMENT); // 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID); //  支付状态 0未支付 1已支付 2退款
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee()); //收货人
        orders.setUserName(user.getName()); //下单人

        ordersMapper.insert(orders);
        log.info("订单id：{}", orders.getId());

        //2、构造订单明细数据，存入order_detail表中
        List<OrderDetail> orderDetailList = new ArrayList<>();
        //循环遍历购物车列表数据，构造订单明细
        cartList.forEach(cart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail, "id");//不拷贝id字段
            //关联订单id
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        });

        String userFullAddress = addressBook.getProvinceName()
                + addressBook.getCityName()
                + addressBook.getDistrictName()
                + addressBook.getDetail();

        checkOutOfRange(userFullAddress);
        //批量插入订单明细数据
        orderDetailMapper.insertBatch(orderDetailList);


        //3、清空购物车
        //删除自己名下的购物车数据
        shoppingCartMapper.delete(userId);



        //4、构造OrdersSubmitVO对象返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();

    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元  这里写死了。正常来说是获取真实的
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        Orders orders = new Orders();
        Orders preorders = ordersMapper.getByNumberAndUserId(ordersPaymentDTO.getOrderNumber(), userId);

        BeanUtils.copyProperties(preorders, orders);

        orders.setPayStatus(Orders.PAID);
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setCancelTime(LocalDateTime.now()); // 如果你想要设置时间
        ordersMapper.update(orders);
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
    }

    @Override
    public PageResult page(int pageNum, int pageSize, Integer status) {
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);


        //条件查找订单
        Page<Orders> page = ordersMapper.pageQuery(ordersPageQueryDTO); //todo 这个查的是订单，但是订单的详细信息，买了什么东西，金额多少这些，是没有的，所以后面还得查个ordersdetail

        // 查找订单详细，并封装入VO
        List<OrderVO> list = new ArrayList<>();

        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId(); //拿到该订单的id去查详细

                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderId);

                // 查询订单详细
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                list.add(orderVO);
            }
        }

        return new PageResult(page.getTotal(), list);
    }

    @Override
    public OrderVO details(Long id) {
        Orders orders = ordersMapper.getById(id);

        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO); //这里orderVO继承了orders。所以他能直接copy  orders里的字段。
        log.info("Order VO:{}", orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    @Override
    public OrderVO cancel(Long id) {
        Orders ordersDB = ordersMapper.getById(id);


        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口 .没有商家权限。这段省略
//            weChatPayUtil.refund(
//                    ordersDB.getNumber(), //商户订单号
//                    ordersDB.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailMapper.getByOrderId(orders.getId()));
        return orderVO;
    }

    @Override
    public void repetition(Long id) {
        // 1. 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 2. 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        // 3. 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 3.1 拷贝除id以外的字段
            BeanUtils.copyProperties(x, shoppingCart, "id");

            // 3.2 设置当前用户id
            shoppingCart.setUserId(userId);

            // 3.3 设置当前时间作为创建时间
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 4. 批量插入购物车对象
        shoppingCartMapper.insertBatch(shoppingCartList);
    }



    private void checkOutOfRange(String userAddress) {
        try {
            // ================= 获取店铺经纬度 ===================
            String shopAddressEncoded = URLEncoder.encode(shopAddress, "UTF-8");
            String query1 = "address=" + shopAddressEncoded + "&output=json&ak=" + ak;
            String geoUrl1 = buildSignedUrl("/geocoding/v3", query1, sk);
            String shopResp = HttpClientUtil.doGet(geoUrl1, new HashMap<>());
            JSONObject shopJson = JSON.parseObject(shopResp);

            if (!"0".equals(shopJson.getString("status"))) {
                throw new OrderBusinessException("店铺地址解析失败");
            }

            JSONObject shopLoc = shopJson.getJSONObject("result").getJSONObject("location");
            String shopLngLat = shopLoc.getString("lat") + "," + shopLoc.getString("lng");

            // ================= 获取用户地址经纬度 ===================
            String userAddressEncoded = URLEncoder.encode(userAddress, "UTF-8");
            String query2 = "address=" + userAddressEncoded + "&output=json&ak=" + ak;
            String geoUrl2 = buildSignedUrl("/geocoding/v3", query2, sk);
            String userResp = HttpClientUtil.doGet(geoUrl2, new HashMap<>());
            JSONObject userJson = JSON.parseObject(userResp);

            if (!"0".equals(userJson.getString("status"))) {
                throw new OrderBusinessException("收货地址解析失败");
            }

            JSONObject userLoc = userJson.getJSONObject("result").getJSONObject("location");
            String userLngLat = userLoc.getString("lat") + "," + userLoc.getString("lng");

            // ================= 路线规划 ===================
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000); // 秒级时间戳
            String query3 = "origin=" + shopLngLat +
                    "&destination=" + userLngLat +
                    "&steps_info=0" +
                    "&ak=" + ak +
                    "&timestamp=" + timestamp;

            String routeUrl = buildSignedUrl("/directionlite/v1/driving", query3, sk);
            String routeResp = HttpClientUtil.doGet(routeUrl, new HashMap<>());

            JSONObject routeJson = JSON.parseObject(routeResp);

            if (!"0".equals(routeJson.getString("status"))) {
                throw new OrderBusinessException("配送路线规划失败");
            }

            JSONArray routes = routeJson.getJSONObject("result").getJSONArray("routes");
            Integer distance = routes.getJSONObject(0).getInteger("distance");

            if (distance > 5000000) {
                throw new OrderBusinessException("超出配送范围");
            }

        } catch (Exception e) {
            throw new OrderBusinessException("地址检查失败：" + e.getMessage());
        }
    }

    private String buildSignedUrl(String path, String query, String sk) throws Exception {
        String toSign = path + "?" + query + sk;
        String encoded = URLEncoder.encode(toSign, "UTF-8");
        String sn = md5(encoded);
        return "https://api.map.baidu.com" + path + "?" + query + "&sn=" + sn;
    }

    private String md5(String s) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digest = md.digest(s.getBytes());
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            sb.append(String.format("%02x", b & 0xff));
        }
        return sb.toString();
    }


}

